package com.lagou.utils;

import com.lagou.pojo.RpcRequest;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class RpcDecoder extends ByteToMessageDecoder {
    private Class<?> clazz;
    private Serializer serializer;

    public RpcDecoder(Class<?> clazz, Serializer serializer) {
        this.clazz = clazz;
        this.serializer = serializer;
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {

        if(byteBuf.readableBytes() < 1)
            return;
        int dataLenth = byteBuf.readInt();
        byte[] data = new byte[dataLenth];
        byteBuf.readBytes(data);
        RpcRequest deserialize = (RpcRequest) serializer.deserialize(this.clazz, data);
        list.add(deserialize);

    }
}
